package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.CommentClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.entity.vo.CommentVo;
import com.atguigu.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author fxy
 * @since 2022-05-15
 */
@RestController
//@CrossOrigin
@RequestMapping("/eduservice/comment")
public class EduCommentController {

    @Autowired
    private EduCommentService eduCommentService;

    @Autowired
    private CommentClient commentClient;

    //分页查询
    @GetMapping("/getCommentList/{page}/{limit}")
    public R getCommentList(@PathVariable long page,@PathVariable long limit,String id){
        Page<EduComment> page1=new Page<>(page,limit);

        QueryWrapper<EduComment> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",id);
        wrapper.orderByDesc("gmt_create");
        eduCommentService.page(page1,wrapper);

        List<EduComment> records = page1.getRecords();
        long current1 = page1.getCurrent();
        long pages = page1.getPages();
        long size = page1.getSize();
        long total = page1.getTotal();
        boolean hasNext = page1.hasNext();
        boolean hasPrevious = page1.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current1);
        map.put("pages", pages);
        map.put("size", size);

        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        //把分页数据获取出来，放到map集合

        return R.ok().data(map);
    }

    //添加评论
    @PostMapping("/addComment")
    public R addComment(@RequestBody CommentVo commentVo,HttpServletRequest request){
        //获取用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //根据用户id查询用户信息
        CommentVo coment = commentClient.getComent(id);

        EduComment eduComment = new EduComment();
        eduComment.setCourseId(commentVo.getCourseId());
        eduComment.setTeacherId(commentVo.getTeacherId());
        eduComment.setMemberId(coment.getMemberId());
        eduComment.setNickname(coment.getNickname());
        eduComment.setAvatar(coment.getAvatar());
        eduComment.setContent(commentVo.getContent());


        eduCommentService.save(eduComment);

        return R.ok();
    }
}

